package com.wskj.supermarket.util;

import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/***
 * 
 * @author Administrator 生日信息的辅助工具类
 */
public class BirthdayUtil {

	private static String pattern = "yyyy-MM-dd";

	/**
	 * 将字符串转化为时间格式,如果传递的字符串不对，就按照当前的时间进行返回
	 * 
	 * @param date
	 *            传入的字符串 yyyy-MM-dd
	 * @return 返回时间
	 * 
	 */
	public static Date convertStringToDate(String date) {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		try {
			Date parse = format.parse(date);
			return parse;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Date();
		}
	}

	public int getYear(Date birthday) {

		
		Calendar calendar = Calendar.getInstance();

		if (birthday.after(calendar.getTime())) {
			System.out.println("传入的时间不能晚于当前系统时间！");
			return 0;
		}
		
		
		int year1=calendar.get(Calendar.YEAR);//当前的年
		int month1=calendar.get(calendar.MONTH);//当前的月
		int day1=calendar.get(Calendar.DAY_OF_MONTH);//当月的天
		
		calendar.setTime(birthday);
		
		int year2=calendar.get(Calendar.YEAR);//生日的年
		int month2=calendar.get(calendar.MONTH);//生日的月
		int day2=calendar.get(Calendar.DAY_OF_MONTH);//生日的天
		
		
		int age=year1-year2;
		
		// 
		//age=month2<month1?age:(month2==month1?(day2<=day1?age:age-1):age);
		
		if (month2>month1 || (month2==month1 && day2>day1)) {			
			age--;
		}
		return age;
	}

}
